package com.etool.action.auth;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

import com.etool.modules.auth.model.NoRequireAuth;
import com.etool.modules.auth.model.NoRequireLogin;
import com.etool.modules.auth.util.loginUtil;
import com.etool.modules.curd.model.Column;
import com.etool.modules.curd.service.CurdService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 登录，注册
 * @author linjia
 *
 */
@NoRequireAuth
@NoRequireLogin
public class WorkerAction extends ActionSupport{
	private HttpServletResponse response=ServletActionContext.getResponse();
	private HttpServletRequest request=ServletActionContext.getRequest();
	private CurdService curdService;
	
	private String target="auth_worker";
	
	private String pinyin;
	private String password;
	
	@Action("login")
	public String login() throws IOException
	{
		List<Map<String, Object>> list=curdService.read(target, Collections.singletonMap("pinyin", (Object)pinyin), 0, 1,null);
		if(list==null || list.size()!=1 || !StringUtils.equals((String)list.get(0).get("password"),password))
		{
			return "login";
		}
		loginUtil.login(request, list.get(0));
		
		return "index";
	}
	
	@Action("register")
	public String register() throws IOException
	{
		List<Column> cols=curdService.desc(target);
		
		Map<String, Object> params=new HashMap<String, Object>();
		
		for(Column item:cols)
		{
			if(item.isAuto_increment() && (StringUtils.isEmpty(request.getParameter(item.getName())) || StringUtils.equals("null",request.getParameter(item.getName()))))
			{
				continue;
			}
			params.put(item.getName(), request.getParameter(item.getName()));
		}
		
		curdService.create(target, params);
		
		loginUtil.login(request, params);
		
		return "index";
	}
	
	public String logout()
	{
		return SUCCESS;
	}
	
	@Action("worker")
	public String worker()
	{
		return SUCCESS;
	}

	public CurdService getCurdService() {
		return curdService;
	}

	public void setCurdService(CurdService curdService) {
		this.curdService = curdService;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getPinyin() {
		return pinyin;
	}

	public void setPinyin(String pinyin) {
		this.pinyin = pinyin;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
